package org.lonetree.tc.webapp.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.lonetree.tc.core.User;
import org.lonetree.tc.core.User.EmailAddress;
import org.lonetree.tc.core.User.Username;
import org.lonetree.tc.core.dao.DAOFactory;
import org.lonetree.tc.core.dao.UserDAO;
import org.lonetree.tc.core.exception.ItemAlreadyExistsException;
import org.lonetree.tc.webapp.forms.UserForm;

public class SelfRegistrationAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception{

		UserForm uuf = (UserForm)form;
		Username uid = new Username(uuf.getUsername());
		
		DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.FactoryImplementation.DB_DAO_FACTORY);
		UserDAO udao = factory.getUserDAO();
		try{
			String pass = uuf.getPassword();
			if(pass == null || pass.trim().equals(""))
				throw new NullPointerException("Please enter a password");
			
			String emailstr = uuf.getEmail();
			EmailAddress em = null;
			if(emailstr != null)
				em = new EmailAddress(emailstr);
			
			User user = udao.createUser(uid);
			user.setFirstName(uuf.getFirstName());
			user.setLastName(uuf.getLastName());
			user.setEmailAddress(em);
			user.setLocation(uuf.getLocation());
			user.setPassword(pass);
			udao.updateUser(user);
			request.getSession().removeAttribute("message");
			return mapping.findForward("success");
		}
		catch(ItemAlreadyExistsException e){
			request.setAttribute("exists", new Object());
			return mapping.findForward("failure");
		}
		catch(Exception e){
			request.getSession().setAttribute("message", e.getMessage());
			return mapping.findForward("failure");
		}
	}
}
